package com.briup.estore.service.impl;

import com.briup.estore.common.dto.AddressAddDTO;
import com.briup.estore.common.dto.AddressUpdateDTO;
import com.briup.estore.common.pojo.Address;
import com.briup.estore.common.pojo.User;
import com.briup.estore.common.utils.BeanCopyUtils;
import com.briup.estore.common.vo.AddressVO;
import com.briup.estore.dao.AddressDao;
import com.briup.estore.dao.UserDao;
import com.briup.estore.dao.impl.AddressDaoImpl;
import com.briup.estore.dao.impl.UserDaoImpl;
import com.briup.estore.service.AddressService;

import java.util.List;

/**
 * @Author briup-adam
 * @Date 2023/8/3 下午2:18
 * @Description
 **/

public class AddressServiceImpl implements AddressService {
    private AddressDao addressDao = new AddressDaoImpl();
    private UserDao userDao = new UserDaoImpl();

    @Override
    public List<AddressVO> findAddresses(Integer userId) {
        List<Address> list = addressDao.findByUserId(userId);
        User user = userDao.getUserById(userId);
        List<AddressVO> vos = BeanCopyUtils.copyList(list, AddressVO.class);
        if (user.getDefaultAddressId() != 0) {
            vos.forEach(i -> {
                if (i.getId() == user.getDefaultAddressId()) {
                    i.setDefaultValue(true);
                }
            });
        }
        return vos;
    }

    @Override
    public void save(AddressAddDTO addressAddDTO,Integer userId) {
        Address address = BeanCopyUtils.copyBean(addressAddDTO, Address.class);
        address.setUserId(userId);
        addressDao.save(address);
    }

    @Override
    public void update(AddressUpdateDTO addressUpdateDTO) {
        Address address = BeanCopyUtils.copyBean(addressUpdateDTO, Address.class);
        addressDao.update(address);

    }

    @Override
    public void setDefaultAddress(Integer userId, Integer addressId) {
        userDao.setDefaultAddress(userId, addressId);
    }

    @Override
    public void cancelDefaultAddress(Integer userId) {
        userDao.cancelDefaultAddress(userId);
    }

    @Override
    public void delete(Integer id) {
        addressDao.deleteById(id);
    }
}
